<template>
  <div class="page-transport">
    <div class="search-bar">
      <el-form
        ref="searchFormRef"
        :inline="true"
        class="search-form"
        :model="searchForm"
        label-width="auto"
        @submit.prevent
      >
        <div class="input-row">
          <el-form-item
            prop="transName"
            :label="$t('transport.name') + ':'"
            class="search-form-item"
          >
            <el-input
              v-model="searchForm.transName"
              :placeholder="$t('transport.name')"
            />
          </el-form-item>
          <el-form-item>
            <div
              class="default-btn primary-btn"
              @click="onSearch(true)"
            >
              {{ $t('station.search') }}
            </div>
            <div
              class="default-btn"
              @click="onResetSearch()"
            >
              {{ $t('station.reset') }}
            </div>
          </el-form-item>
        </div>
      </el-form>
    </div>
    <div class="main-container">
      <div class="operation-bar">
        <div
          v-if="isAuth('shop:transport:save')"
          class="default-btn primary-btn"
          @click.stop="onAddOrUpdate()"
        >
          {{ $t('crud.addTitle') }}
        </div>
        <div
          v-if="isAuth('shop:transport:delete')"
          :class="[dataListSelections.length <= 0 ? 'disabled-btn' : '', 'default-btn']"
          :disabled="dataListSelections.length <= 0"
          @click="onDelete()"
        >
          {{ $t('sys.batchDelete') }}
        </div>
        <div />
      </div>
      <div class="table-con">
        <el-table
          ref="transportTableRef"
          :data="dataList"
          header-cell-class-name="table-header"
          row-class-name="table-row-low"
          style="width: 100%"
          @selection-change="onSelectionChange"
        >
          <el-table-column
            align="center"
            type="selection"
            width="55"
          />
          <el-table-column
            align="left"
            prop="transName"
            width="auto"
            :label="$t('transport.name')"
          >
            <template #default="scope">
              <span class="table-cell-text">{{ scope.row.transName }}</span>
            </template>
          </el-table-column>

          <el-table-column
            align="left"
            prop="imgType"
            :label="$t('transport.chargePrice')"
          >
            <template #default="scope">
              <span>{{
                [$t('transport.byCount'), $t('transport.byWeight'), $t('transport.byVolume')][
                  scope.row.chargeType
                ]
              }}</span>
            </template>
          </el-table-column>
          <el-table-column
            fixed="right"
            align="center"
            :label="$t('publics.operating')"
            width="150"
          >
            <template #default="scope">
              <div class="text-btn-con">
                <div
                  v-if="isAuth('shop:transport:update')"
                  class="default-btn text-btn"
                  @click.stop="onAddOrUpdate(scope.row.transportId)"
                >
                  {{ $t('crud.updateBtn') }}
                </div>

                <div
                  v-if="isAuth('shop:transport:delete')"
                  class="default-btn text-btn"
                  @click.stop="onDelete(scope.row.transportId)"
                >
                  {{ $t('text.delBtn') }}
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-pagination
        v-if="dataList.length"
        :current-page="page.currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="page.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="page.total"
        @update:page-size="onPageSizeChange"
        @update:current-page="onPageChange"
      />
    </div>
    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update
      v-if="addOrUpdateVisible"
      ref="addOrUpdateRef"
      @close="onAddOrUpdateClose"
      @refresh-data-list="refreshChange"
    />
  </div>
</template>

<script setup>
import AddOrUpdate from '@/components/freight-template/index.vue'
import { isAuth } from '@/utils'
import { ElMessageBox, ElMessage } from 'element-plus'

onMounted(() => {
  onGetDataList()
})
const addOrUpdateVisible = ref(false)
const onAddOrUpdateClose = () => {
  addOrUpdateVisible.value = false
}
// 获取数据列表
let tempSearchForm = null // 保存上次点击查询的请求条件
const dataListLoading = ref(false)
const dataList = ref([])
const page = ref({
  total: 0, // 总页数
  currentPage: 1, // 当前页数
  pageSize: 10 // 每页显示多少条
})
const searchForm = reactive({
  transName: ''
})
const onGetDataList = (pageParam, newData = false) => {
  dataListLoading.value = true
  if (newData || !tempSearchForm) {
    tempSearchForm = JSON.parse(JSON.stringify(searchForm))
  }
  http({
    url: http.adornUrl('/shop/transport/page'),
    method: 'get',
    params: http.adornParams(
      Object.assign(
        {
          current: pageParam == null ? page.value.currentPage : pageParam.currentPage,
          size: pageParam == null ? page.value.pageSize : pageParam.pageSize
        },
        tempSearchForm
      )
    )
  }).then(({ data }) => {
    dataList.value = data.records
    page.value.total = data.total
    dataListLoading.value = false

    // 末尾页数据为空重新请求
    if (!dataList.value.length && page.value.currentPage > 1) {
      page.value.currentPage = 1
      onGetDataList()
    }
  })
}
// 新增 / 修改
const addOrUpdateRef = ref(null)
const onAddOrUpdate = id => {
  addOrUpdateVisible.value = true
  nextTick(() => {
    addOrUpdateRef.value?.init(id)
  })
}
// 删除
const dataListSelections = ref([])
const onDelete = id => {
  if (!id && dataListSelections.value.length <= 0) return
  const ids = id ? [id] : dataListSelections.value.map(item => {
    return item.transportId
  })
  ElMessageBox.confirm(
    `${$t('sys.makeSure')}${id ? $t('text.delBtn') : $t('sys.batchDelete')}${$t('text.menu')}?`,
    $t('text.tips'),
    {
      confirmButtonText: $t('crud.filter.submitBtn'),
      cancelButtonText: $t('crud.filter.cancelBtn'),
      type: 'warning'
    }
  )
    .then(() => {
      http({
        url: http.adornUrl('/shop/transport'),
        method: 'delete',
        data: http.adornData(ids, false)
      }).then(() => {
        ElMessage({
          message: $t('publics.operation'),
          type: 'success',
          duration: 1500,
          onClose: () => {
            refreshChange()
          }
        })
      })
    })
    .catch(() => {})
}

// 条件查询
const onSearch = (newData = false) => {
  page.value.currentPage = 1
  onGetDataList(page.value, newData)
}
// 刷新回调用
const refreshChange = () => {
  onGetDataList(page.value)
}
// 多选变化
const onSelectionChange = val => {
  dataListSelections.value = val
}

const searchFormRef = ref(null)
/**
 * 重置表单
 */
const onResetSearch = () => {
  searchFormRef.value.resetFields()
}
const onPageSizeChange = val => {
  page.value.pageSize = val
  onGetDataList()
}
const onPageChange = val => {
  page.value.currentPage = val
  onGetDataList()
}
</script>
